package com.ultimate.management.handler;

import com.alibaba.fastjson.JSON;
import com.ultimate.management.entity.LoginUser;
import com.ultimate.management.entity.SysUser;
import com.ultimate.management.service.SysUserService;
import com.ultimate.management.util.response.JwtUtil;
import com.ultimate.management.util.response.JwtResponse;
import com.ultimate.management.util.response.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author LH
 * @Date 2024/1/23 14:44
 * @PackageName com.ultimate.management.security
 * @Description: 登录成功处理器
 */
@Component
public class LoginSuccessHandler implements AuthenticationSuccessHandler {

    @Autowired
    private JwtResponse jwtResponse;

    //获取用户信息
    @Autowired
    private SysUserService sysUserService;

    //redisUtils工具类
    @Autowired
    private RedisCache redisCache;


    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
        System.out.println("登录成功!");
        response.setContentType("application/json;charset=UTF-8");

        String username = authentication.getName();

        LoginUser loginUser = (LoginUser) authentication.getPrincipal();

        SysUser sysUser = sysUserService.getUserInfo(username);
        Long userId = sysUser.getUserId();
        //设置Token 把用户ID存入Token中
        String token = JwtUtil.createJWT(JSON.toJSONString(userId));

        redisCache.setCacheObject("manager:"+userId,loginUser);

        Map<String, Object> tokenInfo = new HashMap<>();

        //返回Token
        tokenInfo.put("token",token);
        response.getWriter().write(JSON.toJSONString(jwtResponse.ok().data(tokenInfo)));
    }
}
